package com.xsdlr;

import com.xsdlr.handler.DataHandler;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by xsdlr on 2017/3/21.
 */
@Component
public class SchoolDataReader {
    Logger logger = LoggerFactory.getLogger(SchoolDataReader.class);

    private String path;

    public SchoolDataReader(@Value("${school.search.dataPath}") String path) {
        this.path = path;
    }

    public <T> List<T> parse(final DataHandler<T> dataHandler) {
        List<T> result = new LinkedList<>();
        try {
            for (Object oLine: FileUtils.readLines(new File(this.path), "utf-8")) {
                String line = (String) oLine;
                String[] datas = line.split("\\s");
                if(datas.length == 2) {
                    Map map = new HashedMap();
                    map.put("id", datas[0]);
                    map.put("name", datas[1]);
                    result.add(dataHandler.handler(map));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
